package com.yonyou.jrmob.application.ui.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.gzfn.sdkproject.activity.WebViewActivity;
import com.hss01248.dialog.StyledDialog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.request.BaseRequest;
import com.yonyou.jrmob.application.R;
import com.yonyou.jrmob.application.bean.TaskBean;
import com.yonyou.jrmob.application.common.adapter.AppGridAdapter;
import com.yonyou.jrmob.application.tools.UpZipFile;
import com.yonyou.jrmob.application.ui.activity.AllAppActivity;
import com.yonyou.jrmob.application.ui.activity.WebviewActivity;
import com.yonyou.jrmob.application.ui.view.MeasuredRecyclerView;
import com.yonyou.uap.um.base.UMEventArgs;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jrmob.yonyou.com.commonlib.app_config_tool.constant.Constant;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.LogUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.MobUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.NetUtil;
import jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib;
import jrmob.yonyou.com.commonlib.baseui.base.BaseApp_lib;
import jrmob.yonyou.com.commonlib.baseui.fragment.BaseFragmentMob_lib;
import jrmob.yonyou.com.commonlib.login.bean.LoginBean;
import jrmob.yonyou.com.commonlib.login.bean.UserInfoLRY;
import jrmob.yonyou.com.commonlib.vo.AppVO_ap;
import okhttp3.Call;
import okhttp3.Response;

import static android.content.Context.MODE_PRIVATE;
import static jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib.readLocationObject;
import static jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib.readLocationValue;


/**
 * 首页fragment
 *
 * @author Marvin
 */

public class MainAppFragment extends BaseFragmentMob_lib {
    private MeasuredRecyclerView messageRecyclerView;
    private ScrollView rootView;
    private LinearLayout linearlayout ;
    private GridView gridView;
    private Dialog loadingDialog;
    // apk下载百分比
    //private static TextView loading_title_update;
    // apk下载dialog
    //android.support.v7.app.AlertDialog apkDownloadDialog;
    //apk下载路径
    private String apkDownloadPath;
    private static final int UPZIP_SUCCESS = 10000;
    private static final int UPZIP_FAIL = 10001;
    private static final int UPZIP_FINALLY = 10002;//用来取消dialog
    private File zipFile;//下载好的压缩文件
    private List<AppVO_ap> appList = new ArrayList<>();
    private TextView mTvCustomNumber;//客户数
    private TextView mTvAccountNumber;//放款数
    private TextView mTvTotalAccountNumber;//合同总额
    private TextView mTvunDoTasks;//代办任务


    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case UPZIP_SUCCESS:
                    zipFile.delete();
                    openH5App((AppVO_ap) msg.obj);
                    break;
                case UPZIP_FAIL:
                    Toast.makeText(mActivity, "解压失败", Toast.LENGTH_SHORT).show();
                    break;
                case UPZIP_FINALLY:
                    hideLoadingDialog();
                    break;
            }
        }
    };

    @Override
    public View initViews() {
        EventBus.getDefault().register(this);
        rootView = (ScrollView) LayoutInflater.from(getActivity()).inflate(R.layout.fragment_main_app, null);
        gridView = (GridView) rootView.findViewById(R.id.app_main_appList);
        linearlayout = (LinearLayout) rootView.findViewById(R.id.linearlayout);
        initPageTitle();
        messageRecyclerView = (MeasuredRecyclerView) rootView.findViewById(R.id.app_main_messageList);
        initGridView();
        initRecyclerView();
        return rootView;
    }

    /**
     * page title
     */
    private void initPageTitle() {
        mTvCustomNumber = (TextView) rootView.findViewById(R.id.custom_number);
        mTvCustomNumber.setText(readLocationValue(Constant.customer_count));
        mTvAccountNumber = (TextView) rootView.findViewById(R.id.account_number);
        mTvAccountNumber.setText(readLocationValue(Constant.payment_count));
        mTvTotalAccountNumber = (TextView) rootView.findViewById(R.id.account_total_number);
        mTvTotalAccountNumber.setText(readLocationValue(Constant.contract_money));
        mTvunDoTasks = (TextView) rootView.findViewById(R.id.undo_task_number);
        mTvunDoTasks.setText(readLocationValue(Constant.task_count));
    }

    private void initGridView() {
        if (appList != null && appList.size() > 0){
            appList.clear();
        }

        List<AppVO_ap> webAppList = ((BaseActivityMob_lib)getActivity()).readLocationObject(Constant.appsinfo, ArrayList.class);
//        List<AppVO_ap> permissionWebAppList = ((BaseActivityMob_lib)getActivity()).readLocationObject(Constant.permissionAppsInfo, AppVO_ap.class);
//        if (permissionWebAppList == null || permissionWebAppList.size() ==0 || webAppList == null || webAppList.size() == 0 ){
//
//        } else {//查看所有webAPP中有权限的有哪些
//            for (int i = 0; i < permissionWebAppList.size(); i++) {
//                for (int j = 0; j < webAppList.size(); j++) {
//                    if (webAppList.get(j).getAppid().equals(permissionWebAppList.get(i).getApp_code())){
//                        list.add(webAppList.get(j));
//                    }
//                }
//            }
//        }
        if (null !=webAppList && webAppList.size() > 0){
            for (AppVO_ap appVO_ap : webAppList) {
                if (appVO_ap != null){
                    appList.add(appVO_ap);
                }
            }
        }


        AppVO_ap appVO_ap = new AppVO_ap();
        appVO_ap.setAppname("全部");
        appList.add(appVO_ap);
        gridView.setAdapter(new AppGridAdapter(getActivity(), appList));
        int rowNum1;
        if (appList.size() % 4 != 0) {
            rowNum1 = appList.size() / 4 + 1;
        } else {
            rowNum1 = appList.size() / 4;
        }
        int height1 = (int) (rowNum1 * (getResources().getDimension(R.dimen.app_grid_view_item_height) + getResources().getDimension(R.dimen.app_grid_view_item_vertical_spacing))
                - getResources().getDimension(R.dimen.app_grid_view_item_vertical_spacing));
        LinearLayout.LayoutParams lp1 = (LinearLayout.LayoutParams) gridView.getLayoutParams();
        lp1.height = height1;
        gridView.setLayoutParams(lp1);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    AppVO_ap appBean = appList.get(position);
                    if (position == appList.size() - 1) {//全部
                        getActivity().startActivity(new Intent(getActivity(), AllAppActivity.class));
                    } else if ("工作日历".equals(appBean.getAppname())) {
                        startActivity(new Intent("com.yonyou.jrmob.contacts.schedule.activity.ScheduleActivity"));
                    } else if (Constant.EXTRA_H5_APP.equals(appBean.getAppname())) {
                        Intent intent = new Intent(getActivity(), WebviewActivity.class);
                        intent.putExtra(WebviewActivity.INTENT_URL, "https://www.juxinli.com/OrgSpa/#/auth/ygrzzl2/apply");
                        startActivity(intent);
                    } else if (Constant.EXTRA_H5_YIDONGSHENPI.equals(appBean.getAppname())) {
                        Intent intent = new Intent(getActivity(), WebviewActivity.class);
                        intent.putExtra(WebviewActivity.INTENT_URL, Constant.EXTRA_H5_YIDONGSHENPI_URL);
                        startActivity(intent);
                    } else if (Constant.EXTRA_H5_CHEEGU.equals(appBean.getAppname())) {
                        //参数1：activity
                        //参数2:服务提供方所提供的登录标识
                        //参数3：渠道id
                        //参数4：用户手机号
                        WebViewActivity.into(getActivity(),"230d3b5d7dc74684956ea10c8c6f0c68","123456789","13328743993");
                    } else {//H5
                        if (isH5AppExists(appBean)){
                            openH5App(appBean);
                        } else {
                            downloadH5App(appBean);
                        }
                    }

                } catch (Exception e) {
                    LogUtils.e(e);
                    if (null != mActivity) {
                        mActivity.showToast(e.getMessage());
                    }
                    e.printStackTrace();
                }
            }
        });
    }

    private void openH5App(AppVO_ap appBean) {
        try {
            //跳转到OpenSummerActivity显示index.html
            String activityname = "com.yonyou.jrmob.lryapp.activity.OpenSummerActivity";
            // 设置要启动的界面
            Class classname = null;
            classname = Class.forName(activityname);
            // 启动
            Intent intent = new Intent(mActivity, classname);
            //intent.putExtra("appidversion", appBean.getAppid() + appBean.getWebversion());
            //intent.putExtra("startPage", "html/loanhistory.html");
            intent.putExtra("AndroidFilePath",
                    "file://" + apkDownloadPath + appBean.getAppid() + appBean.getWebversion() + "/www/");
            LogUtils.e("AndroidFilePath","file://" + apkDownloadPath + appBean.getAppid() + appBean.getWebversion() + "/www/");
            startActivityForResult(intent, 1);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private boolean isH5AppExists(AppVO_ap appBean) {
        File file = new File(apkDownloadPath + appBean.getAppid() + appBean.getWebversion());
        if (file.exists()){
            long fileSize = mActivity.getTotalSizeOfFilesInDir(file);
            if (fileSize == 0) {
                return false;
            }
            return true;
        }
        return false;
    }

    private void downloadH5App(final AppVO_ap appBean) {
        if (!NetUtil.isNetConnected(getActivity())) {
            mActivity.showMessage("网络未连接,请检查");
            return;
        }
        if (!NetUtil.isAvailable()) {
            mActivity.showMessage("网络不可用,请检查");
            return;
        }
        OkGo.get(appBean.getWebzipurl())//
                .tag(this)//
                .execute(new FileCallback(apkDownloadPath, appBean.getAppid() + appBean.getWebversion() + ".zip") {  //文件下载时，需要指定下载的文件目录和文件名
                    @Override
                    public void onSuccess(File file, Call call, Response response) {
                        // file 即为文件数据，文件保存在指定目录
                        upZipFile(appBean);
                    }

                    @Override
                    public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                        //这里回调下载进度(该回调在主线程,可以直接更新ui)
                        if (progress < 1){
                            //loading_title_update.setText(((int) (progress * 100)) +"%");
                            StyledDialog.updateLoadingMsg("已加载"+((int) (progress * 100)) +"%");
                        }
                    }

                    @Override
                    public void onBefore(BaseRequest request) {
                        //apkDownloadDialog = loadingDialogTitle_update(mActivity, "下载中", false);
                        loadingDialog = StyledDialog.buildLoading("加载中！").setCancelable(false,false).show();
                    }
                });
    }


    private void upZipFile(final AppVO_ap appBean) {
       /* if (loading_title_update != null) {
            loading_title_update.setText("正在安装...");
        }*/
        StyledDialog.updateLoadingMsg("正在安装...");
        zipFile = new File(apkDownloadPath + appBean.getAppid() + appBean.getWebversion() + ".zip");
        if (!zipFile.exists()){
            mActivity.showToast("压缩文件不存在");
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                int result = 0;
                try {
                    result = UpZipFile.upZipFile(zipFile, apkDownloadPath + appBean.getAppid() + appBean.getWebversion());
                    if (0 == result) {  // 说明解压成功
                        hideLoadingDialog();
                        Message message = Message.obtain();
                        message.what = UPZIP_SUCCESS;
                        message.obj = appBean;
                        mHandler.sendMessage(message);
                    } else {// 解压失败提示
                        hideLoadingDialog();
                        Message message = Message.obtain();
                        message.what = UPZIP_FAIL;
                        mHandler.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    hideLoadingDialog();
                    Message message = Message.obtain();
                    message.what = UPZIP_FINALLY;
                    mHandler.sendMessage(message);
                }
            }
        }).start();
    }


    /**
     * 隐藏下载进度
     */
    public void hideLoadingDialog(){
        if (null != loadingDialog && loadingDialog.isShowing()){
            loadingDialog.dismiss();
        }
    }

    /**
     * 得到自定义的progressDialog 有title
     *
     * @param
     * @param
     * @param
     * @return
     */
    /*private android.support.v7.app.AlertDialog loadingDialogTitle_update(Context context, String title, boolean isCancel) {


        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.dialog_loading_tv, null);// 得到加载view

        // title
        loading_title_update = (TextView) v.findViewById(R.id.tv_loading_title);
        loading_title_update.setText(title);

        ImageView animationIV = (ImageView) v.findViewById(R.id.main_img_loading);
        AnimationDrawable animationDrawable = (AnimationDrawable) animationIV.getDrawable();
        //开始动画
        animationDrawable.start();

        android.support.v7.app.AlertDialog loadingDialog = new android.support.v7.app.AlertDialog.Builder(context, R.style.DialogStyle)
                .setView(v)
                .create();

        loadingDialog.setCancelable(isCancel);
        loadingDialog.setCanceledOnTouchOutside(false);
        loadingDialog.show();

        return loadingDialog;

    }*/



    private void initRecyclerView() {
        ArrayList<TaskBean.DataBeanX.DataBean> messageBeanArrayList = mActivity.readLocationObject(Constant.task_list, ArrayList.class);
        if (messageBeanArrayList == null || messageBeanArrayList.size() == 0){
            return;
        }
        messageRecyclerView.setItemAnimator(new DefaultItemAnimator());
        messageRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        /*设置rv的嵌套滑动为false*/
        messageRecyclerView.setNestedScrollingEnabled(false);
        messageRecyclerView.setAdapter(new CommonAdapter<TaskBean.DataBeanX.DataBean>(getActivity(), R.layout.home_message_item, messageBeanArrayList) {
            @Override
            protected void convert(ViewHolder holder, final TaskBean.DataBeanX.DataBean homeMessageBean, int position) {
                holder.setText(R.id.home_message_time, homeMessageBean.getStartTime()+"提交人:"+homeMessageBean.getStartParticipantName());
                holder.setText(R.id.hom_message_title, homeMessageBean.getTaskName());
                holder.setText(R.id.home_message_processName,homeMessageBean.getProcessInstanceName());
                        holder.itemView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(getActivity(), WebviewActivity.class);
                                UserInfoLRY userInfoLRY = readLocationObject(Constant.userInfoLry, UserInfoLRY.class);
                                intent.putExtra(WebviewActivity.INTENT_URL, Constant.EXTRA_H5_YIDONGSHENPI_URL
                                + "?token=" + readLocationValue("login_token")
                                + "&task_id=" + homeMessageBean.getId()
                                + "&processInstanceId=" + homeMessageBean.getProcessInstanceId()
                                + "&processDefinitionId="+homeMessageBean.getProcessDefinitionId()
                                + "&activityId="+homeMessageBean.getActivityId()
                                + "&usercode="+userInfoLRY.getUser_id()
                                + "&tenantid="+userInfoLRY.getTenant_id()
                                + "&u_logints="+readLocationValue("login_u_logints")
                                + "&processKey="+homeMessageBean.getProcessKey()
                                + "&businessKey="+homeMessageBean.getBusinessKey());
                        startActivity(intent);
                    }
                });
            }


        });
    }

    @Override
    public void initData() {
//        callService();
        apkDownloadPath = mActivity.getDownloadPath();
    }

//    private void callService() {
//        try {
//            JSONObject json = new JSONObject();
//
//            json.put("transtype", Constant.TRANSTYPE_HOME_PAGE);
//            json.put("user_code", "11");
//            json.put("uuidToken", Constant.TOKEN);
//            if (!CommonUtil.isNetworkConnected(getActivity())) {
//                CommonUtil.showToast(getActivity(), "当前网络不可用,请检查!");
//                return;
//            }
//            loadingDialog = StyledDialog.buildMdLoading().show();
//            MAServices_gkh.callMACommonService(getActivity(), new ServiceCallback() {
//                @Override
//                public void execute(JSONObject jsonObject) {
//                    StyledDialog.dismiss(loadingDialog);
//                    LogUtils.e("首页数据：" + jsonObject.toString());
//                    try {
//                        JSONObject obj = (JSONObject) jsonObject.opt("result");
//                        // 有错误的时候
//                        if (null != obj && obj.optString("retflag").equals("1")) {
//                            String msg = obj.optString("message");
//                            if (!msg.isEmpty() || !msg.equals("0")) {
//                                ((BaseActivityMob_lib) getActivity()).showMessage(msg);
//                            }
//                            return;
//                        }
//
//                        Gson gson = new Gson();
//                        data = gson.fromJson(obj.toString(), HomePageBean.class);
//                        if (data.getApp_arr() != null && data.getApp_arr().size() != 0) {
//                            initGridView();
//                        }
//                        if (data.getNotify_arr() != null && data.getNotify_arr().size() != 0) {
//                            initRecyclerView();
//                        }
//                    } catch (Exception e1) {
//                        e1.printStackTrace();
//                    }
//                }
//
//                @Override
//                public void error(String s, String s1) {
////                    StyledDialog.dismiss(loadingDialog);
//                    if (loadingDialog != null && loadingDialog.isShowing()) {
//                        loadingDialog.cancel();
//                    }
//                    LogUtils.e(s + " === " + s1);
//                }
//            }, json);
//        } catch (Exception e) {
//            StyledDialog.dismiss(loadingDialog);
//            e.printStackTrace();
//        }
//    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onEventMainThread(String s) {
        if (!TextUtils.isEmpty(s) && s.equals("finised")){
            initRecyclerView();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        //取消所有请求
        OkGo.getInstance().cancelAll();

        EventBus.getDefault().unregister(this);
    }
}
